<?php
/**
 * Created by PhpStorm.
 * User: 10838
 * Date: 2017/10/26
 * Time: 10:25
 */
namespace app\admin\controller;
use app\admin\model\HelpModel;
use think\Validate;

class Help extends Base{

    public function index(){
        $data = HelpModel::order('sort','desc')->paginate("10");
        $this->assign("data",$data);
        $this->assign("page",$data->render());
        return view('index');
    }

    public function add(){
        return view('add');
    }
    public function add_from(){
        if(request()->isPost()){
            $model = new HelpModel();

            $validate   = $this->val($_POST);
            $result   = $validate->check($_POST);
            if(!$result){

               $this->error($validate->getError());
            }else{
                $model->problem = $_POST["problem"];
                $model->answer = $_POST['answer'];
                $model->sort = $_POST['sort'];
                $model->time = time();
               $re = $model->save();
                if($re){
                    $this->success('添加成功！','admin/help/index');
                }else{
                    $this->error('添加失败');
                }
            }

        }else{
            $this->error('非法提交');
        }
    }

    public function edit($id){
       $data = HelpModel::get($id);
        $this->assign("data",$data);
        return view('edit');
    }

    public function edit_from(){
        if(request()->isPost()){
         $validate = $this->val();
            $result = $validate->check($_POST);
            if(!$result){
                $this->error($validate->getError());
            }else{
                $model = HelpModel::get($_POST['id']);
                $model->problem =$_POST['problem'];
                $model->answer = $_POST['answer'];
                $model->sort = $_POST['sort'];
                $re = $model->save();
                if(isset($re)){
                    $this->success("修改成功",'admin/help/index');
                }else{
                    $this->error('修改失败！');
                }

            }


        }else{
            $this->error("非法操作！");
        }
    }

    public function del(){
        $model = HelpModel::get($_POST['help_id']);
        $re =$model->delete();
        var_dump($re);
    }

    protected function val(){
        $rule = [
            'problem'  => 'require',
            'answer'   => 'require',
            'sort' => 'number',
        ];
        $msg = [
            'problem.require'=>'问题不能为空！',
            'answer.require'=>"答案不能为空！",
            'sort.number'=>"排序只能为数字!"
        ];
        $validate = new Validate($rule,$msg);
        return $validate;
    }





}